<template>
	<view class="m-approveList">
		<view v-if="!isEmpty">
			<view class="part" v-for="(approvalRow,keyIndex) in approvalList" :key="keyIndex"
				style="margin-bottom: 10px;">
				<view class="pf">
					<view class="label">流程</view>
					<view class="pd">
						<view>
							<view class="flex-box f-r">
								<view class="mark1 npd">
									<view class="line1">
										<view>
											<view class="dis-ib">
												<view class="img1">
													<text>{{ approvalRow.approvalNodeList[0].node[0].Creater }}</text>
													<image style="width: 14px; height: 14px;margin-right: 4px;"
														class="sf" :src="imageForm.success" />
												</view>
											</view>
										</view>
										<view class="line-li1"></view>
									</view>
								</view>
								<view class="flex-main npd">
									<view>
										<view>
											<text>发起审批</text>
											<text
												class="ap-d">{{ approvalRow.approvalNodeList[0].node[0].CreateTime.split('.')[0].replace(/T/g, '') }}</text>
										</view>
										<view class="f-sub">
											{{ approvalRow.approvalNodeList[0].node[0].Creater }}
										</view>
									</view>
									<view class="pl"></view>
								</view>
							</view>
						</view>
						<view v-for="(row, index) in approvalRow.approvalNodeList" :key="index">
							<view class="flex-box f-r" v-if="row.node[0].ApprovalSort !== 0">
								<view class="mark1 npd">
									<view class="line1">
										<view>
											<view class="dis-ib">
												<view class="img1">
													<text
														v-if="row.node.length === 1 && row.node[0].CurrentApprovalIDs.length === 1 && row.type === 0">
														{{ row.node[0].CurrentApprovalIDs[0] }}
													</text>

													<uni-icons v-else-if="row.type === 1" type="sound" size="28"
														color="#fff" style="padding-top: 7px;" />

													<uni-icons v-else type="staff" size="28" color="#fff"
														style="padding-top: 7px;" />

													<image style="width: 14px; height: 14px;margin-right: 4px;"
														class="sf"
														v-if="approvalRow.level === row.index - 2 && row.type === 1 && row.node[0].Approve !== 0"
														:src="imageForm.success" />
													<image style="width: 14px; height: 14px;margin-right: 4px;"
														class="sf" v-if="approvalRow.level >= row.index - 1"
														:src="getApprovalTagImg(row)" />
												</view>
											</view>
										</view>
										<view class="line-li1"
											v-if="index !== approvalRow.approvalNodeList.length - 1" />
									</view>
								</view>
								<view class="flex-main npd">
									<view>
										<view>
											<view class="x-bc">
												<view class="x-f">
													<text style="vertical-align: middle;"
														v-if="row.type === 1">抄送人</text>
													<text style="vertical-align: middle;" v-else>
														{{ row.department ? row.department : '审批人' }}
													</text>
													<view>
														<u-icon name="more-circle-fill" color="#afd6ff" size="20"
															@click="showMore(row)"
															style="vertical-align: middle;padding-left: 5px;" />
													</view>
												</view>

												<text class="ap-d"
													v-if="approvalRow.level === row.index - 2 && row.type === 1 && row.node[0].Approve !== 0">
													{{ row.node[0].ApproveTime }}
												</text>
												<text class="ap-d" v-if="approvalRow.level >= row.index - 1">
													{{ row.node[0].ApproveTime }}
												</text>
											</view>

											<view class="f-sub" v-if="row.showMore">
												<text
													v-if="row.node.length === 1 && row.node[0].CurrentApprovalIDs.length === 1">
													{{ row.node[0].CurrentApprovalIDs[0] }}
												</text>
												<text
													v-if="row.node.length === 1 && row.node[0].CurrentApprovalIDs.length > 1 && row.type === 0">
													{{ row.node[0].CurrentApprovalIDs.length }}人或签
												</text>
												<text v-if="row.node.length > 1 && row.type === 0">
													{{ row.node.length }}人会签
												</text>
												<text
													v-if="row.node.length > 1 && !checkIsSingle(row) && row.type === 0">
													多人审核
												</text>
												<text
													v-if="approvalRow.level === row.index - 2 && row.type === 1 && row.node[0].Approve !== 0">
													（已抄送）
												</text>
												<text v-if="approvalRow.level >= row.index - 1">
													（{{ getApprovalText(row) }}）
												</text>
											</view>
										</view>
										<view class="hq" v-if="row.showMore">
											<!-- 或签 -->
											<view class="wh"
												v-if="row.node.length === 1 && row.node[0].CurrentApprovalIDs.length > 1">
												<view class="dis2-ib"
													v-for="(item, itemIndex) in row.node[0].CurrentApprovalIDs"
													:key="itemIndex">
													<view class="dis-ib">
														<view class="img">
															<text>{{ cutStr(item) }}</text>
															<image style="width: 14px; height: 14px;margin-right: 4px;"
																class="sf"
																v-if="item === row.node[0].Approver && approvalRow.level >= row.index - 1 && row.node[0].Approve !== 0"
																:src="row.node[0].Approve === 1 ? imageForm.success : imageForm.fail" />
														</view>
														<view class="ap-n">{{ item }}</view>
													</view>
													<view class="dis3-ib"
														v-if="itemIndex !== row.node[0].CurrentApprovalIDs.length - 1 && row.type === 0">
														/
													</view>
													<view class="dis3-ib" v-if="row.type === 1"> </view>
												</view>
											</view>
											<!-- 会签 -->
											<view class="wh" v-if="row.node.length > 1 && checkIsSingle(row)">
												<view class="dis2-ib" v-for="(item, itemIndex) in row.node"
													:key="itemIndex">
													<view class="dis-ib">
														<view class="img">
															<text>{{ cutStr(item.CurrentApprovalIDs[0]) }}</text>
															<image style="width: 14px; height: 14px;margin-right: 4px;"
																class="sf"
																v-if="item.Approver && item.Approver === item.CurrentApprovalIDs[0] && approvalRow.level >= row.index - 1 && item.Approve !== 0"
																:src="item.Approve === 1 ? imageForm.success : imageForm.fail" />
														</view>
														<view class="ap-n">{{ item.CurrentApprovalIDs[0] }}</view>
													</view>
													<view class="dis3-ib"
														v-if="itemIndex !== row.node.length - 1 && row.type === 0">
														+
													</view>
												</view>
											</view>
											<!-- 多人审核 -->
											<view class="wh" v-if="row.node.length > 1 && !checkIsSingle(row)">
												<view class="dis2-ib" v-for="(item, itemIndex) in row.node"
													:key="itemIndex">
													<view class="dis2-ib"
														v-for="(detail, detailIndex) in item.CurrentApprovalIDs"
														:key="detailIndex">
														<view class="dis-ib">
															<view class="img">
																<text>{{ cutStr(detail) }}</text>
															</view>
															<view class="ap-n">{{ detail }}</view>
														</view>
														<view class="dis3-ib" v-if="itemIndex !== row.node.length - 1">
															/
														</view>
													</view>
												</view>
											</view>
										</view>
										<view class="pl">
											<view class="plpd" v-for="item in row.node" :key="item.ApprovalSort">
												<view>
													<text v-if="item.ApprovalContent" :class="'ac-' + item.Approve">
														{{ item.Approver }}:
													</text>
													<text v-if="item.ApprovalContent" :class="'ac-' + item.Approve">
														"{{ item.ApprovalContent }}"
													</text>
												</view>

												<view class="piccontent" v-if="item.Imgs">
													<view class="van-uploader">
														<view class="van-uploader__wrapper x-f"
															style="flex-wrap: wrap;">
															<view class="van-uploader__preview"
																v-for="(imgItem, imgItemIndex) in (item.Imgs ? item.Imgs.split(',') : [])"
																:key="imgItemIndex">
																<view class="van-image van-uploader__preview-image"
																	style="overflow: hidden; border-radius: 4px;width:60px;height:60px;"
																	@click="previewItemImage(item.Imgs, imgItemIndex)">
																	<image
																		style="width: 40px; height: 40px;margin-right: 4px;object-fit: cover;"
																		:src="processImageUrl(imgItem)"
																		class="van-image__img" />
																</view>
															</view>
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>

	</view>
</template>

<script setup lang="ts">
	import {
		ref, computed, onMounted
	} from 'vue';
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	// 定义类型接口
	interface Option {
		keyName : string;
		keyValue : string;
		Status : number;
		globalData ?: {
			physicalTableName : string;
		};
	}
	interface Person {
		UserID : string;
		UserName : string;
		EmplName : string;
	}

	interface ApprovalNode {
		ApprovalSort : number;
		CurrentApprovalIDs : string[];
		Approve : number;
		Approver : string;
		ApproveTime : string;
		ApprovalContent : string;
		Imgs : string;
		[key : string] : any;
	}

	interface ApprovalRowNode {
		index : number;
		type : number;
		department ?: string;
		node : ApprovalNode[];
		showMore ?: boolean;
		[key : string] : any;
	}

	interface ApprovalListRow {
		level : number;
		approvalNodeList : ApprovalRowNode[];
	}
	const props = defineProps<{
		option : Option;
	}>();
	const imageForm = computed(() => {
		return {
			'success': "/uni_modules/mc-ui/static/image/success.png",
			'fail': "/uni_modules/mc-ui/static/image/fail.png",
			'doing': "/uni_modules/mc-ui/static/image/doing.png"
		}
	});
	// 方法定义
	const processImageUrl = (url : string) => {
		if (!url) return '';
		url = url.trim();

		const urlRegular = (value : string) => /^((https|http|ftp|rtsp|mms):\/\/)/.test(value);

		return urlRegular(url) ? url : `${mainStore.appConfigInfo.IPAgreement}${mainStore.appConfigInfo.serverIP}${url}`;
	};
	const showMore = (row : ApprovalRowNode) => {
		row.showMore = !row.showMore;
	};
	const previewItemImage = (imgs : string, index : number) => {
		const array = imgs.split(',');
		const newImgArr = array.map(item => processImageUrl(item));
		uni.previewImage({
			cancel: "取消",
			urls: newImgArr,
		})
		// @ts-ignore
		// plus.nativeUI.previewImage(newImgArr, {
		// 	current: index,
		// 	loop: true,
		// 	onLongPress: (e : any) => {
		// 		// @ts-ignore
		// 		plus.nativeUI.actionSheet({
		// 			cancel: "取消",
		// 			buttons: [{ title: "保存到手机" }]
		// 		}, (event : any) => {
		// 			if (event.index > 0) {
		// 				saveImgToLocal(e.url);
		// 			}
		// 		});
		// 	}
		// });
	};
	const saveImgToLocal = (url : string) => {
		uni.downloadFile({
			url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							// @ts-ignore
							plus.nativeUI.toast("已保存到相册", {
								icon: imageForm.value.success
							});
							uni.removeSavedFile({
								filePath: res.tempFilePath
							});
						},
						fail: () => {
							// @ts-ignore
							plus.nativeUI.toast("图片保存失败，请检查权限");
							uni.removeSavedFile({
								filePath: res.tempFilePath
							});
						}
					});
				}
			}
		});
	};
	const getApprovalTagImg = (row : ApprovalRowNode) => {
		if (row.node.length === 1) {
			switch (row.node[0].Approve) {
				case 0:
					return imageForm.value.doing;
				case 1:
					return imageForm.value.success;
				case 2:
					return imageForm.value.fail;
				default:
					return '';
			}
		} else {
			let imgstr = '';
			let z = 0;

			for (const i in row.node) {
				if (row.node[i].Approve === 1) {
					z++;
				}
				if (row.node[i].Approve === 2) {
					imgstr = imageForm.value.fail;
					break;
				}
			}

			if (imgstr) return imgstr;

			if (z === 0) {
				imgstr = imageForm.value.doing;
			} else {
				imgstr = row.node.length === z
					? imageForm.value.success
					: imageForm.value.doing;
			}

			return imgstr;
		}
	};
	const getApprovalText = (row : ApprovalRowNode) => {
		if (row.type === 1) {
			return row.node[0].Approve === 0 ? '未抄送' : '已抄送';
		} else {
			if (row.node.length === 1) {
				switch (row.node[0].Approve) {
					case 0:
						return '审批中';
					case 1:
						return '已同意';
					case 2:
						return '已拒绝';
					default:
						return '';
				}
			} else {
				let str = '';
				let z = 0;

				for (const i in row.node) {
					if (row.node[i].Approve === 1) {
						z++;
					}
					if (row.node[i].Approve === 2) {
						str = '已拒绝';
						break;
					}
				}

				if (str) return str;

				if (z === 0) {
					str = '审批中';
				} else {
					str = row.node.length === z ? '已同意' : `${z}人同意`;
				}

				return str;
			}
		}
	};

	const cutStr = (str : string) => {
		return str ? str.substring(str.length - 2) : '';
	};

	const checkIsSingle = (row : ApprovalRowNode) => {
		for (const i in row.node) {
			if (row.node[i].CurrentApprovalIDs.length > 1) {
				return false;
			}
		}
		return true;
	};

	console.log(props.option);
	const BaseScreenParm = props.option as any;
	let isEmpty = ref(false);

	let personList = ref<any>([]);
	// 预先构建映射（只需要执行一次）
	const personMap = new Map();

	function getCkUserList() {
		request({
			url: 'getCkUserList',
			method: 'POST',
			data: {

			},
			success(ret : any) {
				if (ret.status == 200) {
					personList.value = ret.data.ds;
					for (const person of ret.data.ds) {
						personMap.set(person["UserID"], person);
					};
					initPageData();
				}

			}

		});
	};
	let finalResult = ref(0);
	const approvalList = ref<any>([]);
	function initPageData() {

		request({
			url: 'Select_FlowLog1',
			method: 'POST',
			data: {
				P_PKValue: BaseScreenParm.keyValue,
				P_TableName: BaseScreenParm.globalData.physicalTableName
			},
			success(ret : any) {
				if (ret.status == 200) {
					if (ret.data.ds.length) {
						if (ret.data.ds[ret.data.ds.length - 1].Approve == 1) {
							finalResult.value = 1;
						}
						let data = [];

						for (let i in ret.data.ds) {

							ret.data.ds[i].CurrentApprovalIDs = ret.data.ds[i].CurrentApprovalIDs.replace(/^,+/, "").replace(/,+$/, "").split(',');

							for (let c in ret.data.ds[i].CurrentApprovalIDs) {
								let row = personMap.get(+ret.data.ds[i].CurrentApprovalIDs[c]);
								if (row) {
									ret.data.ds[i].CurrentApprovalIDs[c] = row.EmplName;
								}

							}

							if (data.indexOf(ret.data.ds[i].AuditID) == -1) {
								data.push(ret.data.ds[i].AuditID);
							}
						};

						const approvalListData = [];
						// 遍历数据，处理每个审批ID对应的审批节点
						for (const auditId of data) {
							const approvalNodeList : ApprovalRowNode[] = [];
							let currentLevel = 0;
							let finalApprovalLevel = 0;
							const dataset = ret.data.ds;
							const datasetLength = dataset.length;

							// 遍历审批记录数据集
							for (const record of dataset) {
								// 只处理当前审批ID对应的记录
								if (auditId === record.AuditID) {
									// 处理未审批状态且当前级别未设置的情况
									if (record.Approve === 0 && !currentLevel) {
										currentLevel = record.ApprovalSort;
									}

									// 处理已审批状态且是最后一条记录的情况
									if (record.Approve === 1 && dataset.indexOf(record) === datasetLength - 1) {
										currentLevel = record.ApprovalSort;
									}

									// 处理驳回状态且最终级别未设置的情况
									if (record.Approve === 2 && !finalApprovalLevel) {
										finalApprovalLevel = record.ApprovalSort;
									}

									// 如果是最后一个审批ID且状态为驳回，设置最终结果
									if (record.Approve === 2 && auditId === data[data.length - 1]) {
										finalResult.value = 2;
									}

									// 查找当前审批排序对应的节点
									const existingNode = approvalNodeList.find(
										node => node.index === record.ApprovalSort
									);

									// 存在则添加到现有节点，否则创建新节点
									if (existingNode) {
										existingNode.node.push(record);
									} else {
										approvalNodeList.push({
											index: record.ApprovalSort,
											type: record.FlowType,
											department: record.ApprovalName,
											node: [record],
											showMore: false
										});
									}
								}
							}

							// 添加处理好的审批节点列表到结果中
							approvalListData.push({
								level: finalApprovalLevel ? (finalApprovalLevel - 1) : (currentLevel - 1),
								approvalNodeList
							});
						}

						approvalList.value = approvalListData;

						isEmpty.value = false;
					} else {
						isEmpty.value = true;
					}

				}
			}
		});
	};

	onMounted(() => {
		getCkUserList()
	})
</script>

<style lang="scss">
	.m-approveList {
		height: 100%;
	}

	.BtnBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100px;
		position: fixed;
		top: 50%;
		left: 0%;
		width: 100%;
		opacity: 0.7;
	}

	.part {
		padding: 15px 15px 0 15px;
	}

	.part .pf {
		border-radius: 6px;
		box-shadow: 0px 1px 5px rgb(200, 198, 198);
		background-color: #fff;
		overflow: hidden;
	}

	.textarea {
		display: block;
	}

	.label {
		padding: 10px 16px;
	}

	.ap-f {
		border-bottom: 1px solid #f7f7f7;
	}

	.f-r {
		/* padding: 17px 0; */
	}

	.mark {
		padding: 17px 15px;
	}

	.mark1 {
		padding: 17px 5px 17px 15px;
		position: relative;
	}

	.f-sub {
		color: #969799;
		font-size: 26rpx;
		margin-top: 4px;
	}

	.line {
		position: relative;
		width: 30px;
	}

	.line1 {
		width: 60px;
	}

	.line-sq {
		display: inline-block;
		width: 11px;
		height: 11px;
		border-radius: 6px;
		background: #d6d6d6;
		position: absolute;
		left: 0;
		top: 12px;
	}

	.line-li {
		display: inline-block;
		width: 1px;
		background: #d6d6d6;
		position: absolute;
		left: 5px;
		top: -17px;
		bottom: -17px;
	}

	.line-li1 {
		display: inline-block;
		background: #d6d6d6;
		position: absolute;
		top: 52px;
		left: 35px;
		width: 3px;
		bottom: 10px;
	}

	.pd {
		padding: 16px 0;
	}

	.ap-r {
		text-align: right;
		padding-right: 10px;
		/* margin: -8px 0; */
		padding-top: 10px;
	}

	.ap-d {
		text-align: right;
		padding-right: 10px;
		color: #ccccce;
		font-size: 26rpx;
		float: right;
		padding-top: 3px;
	}

	.img {
		width: 34px;
		height: 34px;
		line-height: 34px;
		text-align: center;
		font-size: 24rpx;
		color: #fff;
		background-color: #3396fb;
		border-radius: 6px;
		margin: 0 auto;
		position: relative;
		user-select: none;
	}

	.img1 {
		width: 44px;
		height: 44px;
		line-height: 44px;
		text-align: center;
		font-size: 26rpx;
		color: #fff;
		background-color: #3396fb;
		border-radius: 6px;
		position: relative;
		user-select: none;
	}

	.dis-ib {
		display: inline-block;
		vertical-align: middle;
		text-align: center;
		min-width: 40px;
	}

	.dis2-ib {
		display: inline-block;
		vertical-align: middle;
		padding-bottom: 3px;
		text-align: center;
	}

	.dis3-ib {
		display: inline-block;
		margin: 0 6px;
		color: #969799;
		vertical-align: top;
		padding-top: 7px;
		text-align: center;
	}

	.ap-n {
		padding-top: 2px;
		font-size: 26rpx;
		color: #969799;
		text-align: center;
	}

	.bottom {
		padding: 8px 15px;
	}

	.part-white {
		padding: 15px;
		background-color: #fff;
		position: relative;
	}

	.title {
		line-height: 40px;
		font-size: 36rpx;
	}

	.title-sub {
		color: #aaacac;
		font-size: 52rpx;
	}

	.ap-res {
		color: #a3a3a3;
		font-size: 30rpx;
		padding-top: 6px;
	}

	.ap-res1 {
		color: #c31616;
		font-size: 30rpx;
		padding-top: 6px;
	}

	.ap-img {
		position: absolute;
		right: 20px;
		bottom: -38px;
		width: 88px;
		opacity: 0.4;
	}

	.form-row {
		padding: 4px 16px;
	}

	.form-label {
		color: #808991;
		font-size: 26rpx;
		user-select: none;
	}

	.form-content {
		padding-top: 5px;
	}

	.npd {
		padding-top: 0;
		overflow-x: auto;
	}

	.pl {
		color: #969799;
		font-size: 32rpx;
		margin: 6px 2px 18px 0;
		min-height: 25px;
		border-bottom: 1px solid #ebedf0;
	}

	.sf {
		width: 16px;
		background: #fff;
		padding: 2px;
		border-radius: 8px;
		position: absolute;
		right: -5px;
		bottom: -2px;
	}

	.select {
		color: #3396fb;
		float: right;
		font-size: 26rpx;
		padding-top: 3px;
		vertical-align: middle;
	}

	// .select a {
	// 	vertical-align: middle;
	// }

	.select image {
		width: 16px;
		vertical-align: middle;
	}

	.hq {
		padding: 10px 10px 0 0;
	}

	.wh {
		white-space: nowrap;
		overflow-x: auto;
		padding-right: 10px;
	}

	.plpd {
		padding-bottom: 5px;
	}

	.pictitle {
		line-height: 24px;
		color: #646566;
		user-select: none;
	}

	.piccontent {
		padding-top: 10px;
		overflow: hidden;
	}

	.van-uploader__preview {
		margin-right: 15px;
	}

	.no {
		text-align: center;
		color: #808991;
		font-size: 28rpx;
	}

	.li1 {
		top: 15px;
	}

	.li2 {
		bottom: 24px;
	}

	.da-c {
		color: #c31616;
	}

	.danger .van-field__control {
		color: #c31616;
	}

	.danger .van-field__label {
		color: #808991;
	}

	.ac-1 {
		color: #03b553;
	}

	.ac-2 {
		color: #c31616;
	}

	.checkbox {
		padding: 25px 5px 10px 10px;
	}

	.jl-remark {
		padding: 5px 0;
		color: #3396fb;
	}

	.memo-l {
		border-bottom: 1px solid rgb(235, 237, 240);
		padding: 4px 0;
	}

	.memo-l:last-child {
		border-bottom: 0;
	}



	[v-cloak] {
		display: none !important;
	}

	.o-y-a {
		overflow-y: auto;
	}

	image {
		vertical-align: middle;
	}

	/* flex相关 */
	.flex-box {
		display: -webkit-flex;
		display: flex;
	}

	.flex-direction-c {
		flex-direction: column;
	}

	.flex-direction-r {
		flex-direction: row;
	}

	.flex-main {
		flex: 1;
	}
</style>